<?php

// +----------------------------------------------------------------------
// | Address api控制器
// +----------------------------------------------------------------------
// | @author fancsen
// +----------------------------------------------------------------------

/**
 * Address api控制器
 * @author fancsen
 */


namespace app\api\controller\v1;

use app\api\validate\Address as AddressValidate;
use app\api\model\UserAddress as AddressModel;
use app\api\model\User as UserModel;
use app\common\lib\exception\ApiException;
use app\api\service\Token as TokenService;
use app\api\controller\BaseController;


class Address extends BaseController
{
    //前置成员变量
    protected $beforeActionList = [
        'checkPrimaryScope' => ['only' => 'getUserAddress,createOrUpdateAddress'] 
    ];

    
    

    /**
     * 获取用户地址信息
     * @return UserAddress
     * @throws UserException
     */
    public function getUserAddress(){
        $uid = TokenService::getCurrentUidByToken();
        $userAddress = AddressModel::where('user_id', $uid)
            ->find();
        if(!$userAddress){
            throw new ApiException('用户不存在',403,70001);
        }
        return show(config('api.success_status'),'ok',$userAddress);
    }

    /**
     * 新增或更新用户第一
     * @http post
     * @param number $id banner的id值
     * @return string
     */
    public function createOrUpdateAddress()
    {
        $validate = new AddressValidate();
        $validate->goCheck();
        //1获取到token
        //2根据token得到uid，查询数据库中是否存在该用户，不存在抛出异常
        //3用户存在则查询数据中是否有该用户的地址，存在则更新，不存在则新增
        
        $uid = TokenService::getCurrentUidByToken();
        $user = UserModel::get($uid);
        
        if($user == null){
            throw new ApiException("用户不存在", 403,70000); 
        }

        $dataArray = $validate->getDatasByRule(input('post.'));
       
        $address = $user->address;
        
        if($address){
            //存在则更新
            $user->address->save($dataArray);
        }else {
            //不存在，新增
            $user->address()->save($dataArray);
        }

        return show(config('api.success_status'),'ok',[],201);
    }

}